<template>
    <a-auto-complete v-model:value="path" style="width: 100%" option-label-prop="value" @change="change" :options="options"></a-auto-complete>
    <br><br>
    <a-alert v-if="showErrorMessage" message="链接格式错误" type="error" />
</template>
<script setup>
import { ref } from 'vue';
import storage from '../../libs/storage';



const path = ref('');
const showErrorMessage = ref(false);
const options = ref([]);

var pathList = storage.get('pathList');
if (!pathList) {
    storage.set('pathList', []);
    pathList = [];
} else {
    options.value = pathList.map(item => {
        return { value: item }
    });
};

var v = new RegExp('^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', 'i');
const change = function () {
    return showErrorMessage.value = !v.test(path.value);
}

const getValue = function (callback) {
    if (!change()) {
        var _value = path.value.split('?')[0]
        path.value = _value;
        var isHave = false;
        for (let i = 0; i < options.value.length; i++) {
            const element = options.value[i];
            if (element.value == _value) {
                isHave = true;
            }
        };
        if (!isHave) {
            storage.set('pathList', [...pathList, _value]);
            options.value.push({
                value: _value,
            })
        }
        callback(null, _value)
    } else {
        callback(true);
    }
}
defineExpose({
    getValue,
})

</script>
<style scoped>
</style>